/**
 * 
 */
package org.crystal.jqweb.config;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


/**
 * @author Crystal
 * 
 */
public class ServletMapping {
	private final Log log = LogFactory.getLog(getClass());
	private   String actionSuffix = "jx";

	public   String  getActionSuffix() {
		return actionSuffix;
	}
	/**
	 * 
	 */
	public ServletMapping(String webXml,String servletName) {
		super();
		// TODO Auto-generated constructor stub
		try {
			
			File file = new File(webXml);
			if (file.exists()) {
				//System.out.println(webXml);
				//System.out.println(servletName);
				DocumentBuilderFactory factory = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(webXml);
				TransformerFactory tranFactory = TransformerFactory
						.newInstance();
				Transformer aTransformer = tranFactory.newTransformer();

				NodeList list = doc.getElementsByTagName("servlet-mapping");
				//System.out.println("actionSuffix for");
				for (int i = 0; i < list.getLength(); i++) {
					// Get element
					Element element = (Element) list.item(i);
					String urlpattern=(((Element) (element.getElementsByTagName("url-pattern")).item(0))).getTextContent();
					String servletname=(((Element) (element.getElementsByTagName("servlet-name")).item(0))).getTextContent();
					//System.out.println("actionSuffix"+i+urlpattern);
					//System.out.println("actionSuffix"+i+servletname);
					if(servletname.endsWith(servletName)&&urlpattern.indexOf(".")!=-1){
						actionSuffix=urlpattern.substring(urlpattern.indexOf(".")+1);
						//System.out.println(urlpattern.substring(urlpattern.indexOf(".")+1));
						//System.out.println("actionSuffix ok:"+actionSuffix);
						log.debug("ServletMapping() actionSuffix :"+actionSuffix);
						break;
					}
				}
			}else{
				log.debug("ServletMapping() "+webXml + " (file name) doesn't found!");
			}
		} catch (Exception e) {
			e.getMessage();
		}

	}
	/*public static void main(String[] args) {
		System.out
		.println(ServletMapping.getInstance("/D:/SoftWare/apache-tomcat-5.5.30/webapps/JqWeb/WEB-INF/web.xml", "JqWeb").getActionSuffix());
		
	}*/
}
